package com.bt.framework.base

import android.app.Dialog
import android.os.Bundle
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.bt.framework.log.XLogger

/**
 *@author:hxm
 *@date: 2025/7/6 23:14
 *@version:
 *@description:DialogFragment基类
 */
abstract class BaseDialogFragment : AppCompatDialogFragment() {
    private var mDialog: BaseDialog? = null

    companion object {
        private var sShowTag: String? = null
        private var sLastTime: Long = 0
    }

    fun show(fragment: Fragment?) {

    }


    override fun show(manager: FragmentManager, tag: String?) {
        super.show(manager, tag)
    }

    override fun show(transaction: FragmentTransaction, tag: String?): Int {
        return super.show(transaction, tag)
    }

    /**
     * 根据 tag 判断这个 Dialog 是否重复显示了
     *
     * @param tag Tag标记
     */
    protected fun isRepeatedShow(tag: String?): Boolean {
        val result = tag == sShowTag && System.currentTimeMillis() - sLastTime < 500
        sShowTag = tag
        sLastTime = System.currentTimeMillis()
        return result
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return if (mDialog != null) {
            mDialog!!
        } else {
            // 不使用 Dialog，替换成 BaseDialog 对象
            BaseDialog(requireActivity()).also { mDialog = it }
        }
    }

    override fun getDialog(): Dialog? {
        return if (mDialog != null) mDialog else super.getDialog()
    }

    fun setDialog(dialog: BaseDialog?) {
        mDialog = dialog
    }

    open class Builder<B : BaseDialog.Builder<B>>(
        /**
         *  获取当前 Activity 对象（仅供子类调用）
         */
        protected val activity: FragmentActivity
    ) : BaseDialog.Builder<B>(activity) {

        /**
         * 获取当前 DialogFragment 对象（仅供子类调用）
         */
        protected var dialogFragment: BaseDialogFragment? = null
            private set

        /**
         * 获取 Fragment 的标记
         */
        protected val fragmentTag: String
            protected get() = javaClass.name

        override fun show(): BaseDialog? {
            val dialog = create()
            try {
                dialogFragment = initDialogFragment()

            } catch (e: Exception) {
                XLogger.e("@BaseDialog, 弹窗show失败$e")
            }
            return dialog
        }

        protected fun initDialogFragment(): BaseDialogFragment {
            return BaseDialogFragment()
        }

    }

}